package com.zx.controller;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zx.entity.Order;
import com.zx.entity.Product;
import com.zx.feign.ProductFeignClient;
import com.zx.service.OrderService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-03-11
 */
@RestController
@RequestMapping("/test/order")
@DefaultProperties(defaultFallback = "defaultFallbcakMethod")
public class OrderController1 {

    @Resource
    private OrderService orderService;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private ProductFeignClient productFeignClient;

//    /**
//     * 查询订单信息
//     *
//     * @param id 订单id
//     * @return 订单
//     */
//    @GetMapping("/{id}")
//    @ResponseStatus(HttpStatus.OK)
//    public String findById(@PathVariable("id") Long id) {
//        // 通过discoveryClient对象获取服务实例，包括ip地址、端口。。一些元数据
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//        ServiceInstance instance = instances.get(0);
//        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/product/1";
//        Product product = restTemplate.getForObject(url, Product.class);
//        return JSON.toJSONString(product);
//    }

    /**
     * 查询订单信息
     *
     * @param id 订单id
     * @return 订单
     */
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
//    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public String findById(@PathVariable("id") Long id) {
        //使用feign组件调用
        return productFeignClient.findById(id);
    }

    public String fallbackMethod(Long id){

        System.out.println("进入降级方法");
        return "进入降级方法";
    }

    /**
     *
     * 默认降级方法
     */
    public String defaultFallbcakMethod(){
        System.out.println("指定默认的降级方法");
        return "指定默认的降级方法";
    }


}
